package Pet.Management.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import Pet.Management.domain.dto.PostDTO;
import Pet.Management.domain.dto.UserDTO;
import Pet.Management.domain.entity.Favorite;
import Pet.Management.domain.entity.Like;
import Pet.Management.domain.entity.Post;
import Pet.Management.domain.entity.User;
import Pet.Management.repository.FavoriteRepository;
import Pet.Management.repository.LikeRepository;
import Pet.Management.repository.PostRepository;
import Pet.Management.repository.UserRepository;
import Pet.Management.service.MessageService;

@RestController
@RequestMapping("/api/favorites")
public class FavoriteController {

    private static final Logger logger = LoggerFactory.getLogger(FavoriteController.class);

    @Autowired
    private FavoriteRepository favoriteRepository;
    
    @Autowired
    private PostRepository postRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private LikeRepository likeRepository;
    
    @Autowired
    private MessageService messageService;
    
    /**
     * 收藏/取消收藏帖子
     */
    @PostMapping("/toggle/{postId}")
    @Transactional
    public ResponseEntity<Map<String, Object>> toggleFavorite(
            @PathVariable Long postId,
            @RequestParam(required = false) Long userId,
            @RequestHeader(value = "Authorization", required = false) String token) {
        
        logger.info("收藏/取消收藏请求：postId={}, userId={}, token={}", postId, userId, token);
        
        // 尝试从请求参数中获取用户ID
        if (userId != null) {
            logger.info("使用请求参数中的userId: {}", userId);
            Optional<User> userOpt = userRepository.findById(userId);
            if (userOpt.isPresent()) {
                return processToggleFavorite(postId, userOpt.get());
            } else {
                logger.warn("找不到指定ID的用户: {}", userId);
            }
        }
        
        // 尝试从请求头中获取token
        if (token == null || token.isEmpty()) {
            logger.warn("未提供Authorization头");
            return ResponseEntity.status(401).build();
        }
        
        // Bearer Token处理
        if (token.startsWith("Bearer ")) {
            logger.info("处理Bearer Token");
            token = token.substring(7);
        }
        
        User user = null;
        try {
            // 尝试将token解析为用户ID
            Long tokenUserId = Long.parseLong(token);
            logger.info("尝试将token作为用户ID解析: {}", tokenUserId);
            Optional<User> currentUser = userRepository.findById(tokenUserId);
            
            if (currentUser.isPresent()) {
                user = currentUser.get();
                logger.info("通过ID找到用户: {}", user.getUsername());
            } else {
                logger.warn("找不到ID为{}的用户", tokenUserId);
            }
        } catch (NumberFormatException e) {
            // 如果token不是有效的用户ID，尝试按用户名查找
            logger.info("token不是数字，尝试作为用户名: {}", token);
            Optional<User> currentUser = userRepository.findByUsername(token);
            if (currentUser.isPresent()) {
                user = currentUser.get();
                logger.info("通过用户名找到用户: {}", user.getUsername());
            } else {
                logger.warn("找不到用户名为{}的用户", token);
            }
        }
        
        if (user == null) {
            logger.warn("无法验证用户身份");
            return ResponseEntity.status(401).build();
        }
        
        return processToggleFavorite(postId, user);
    }
    
    /**
     * 处理收藏/取消收藏的核心逻辑
     */
    private ResponseEntity<Map<String, Object>> processToggleFavorite(Long postId, User user) {
        Optional<Post> postOpt = postRepository.findById(postId);
        if (!postOpt.isPresent()) {
            logger.warn("找不到ID为{}的帖子", postId);
            return ResponseEntity.notFound().build();
        }
        
        Post post = postOpt.get();
        Optional<Favorite> existingFavorite = favoriteRepository.findByUserIdAndPostId(user.getId(), post.getId());
        boolean isFavorited;
        
        try {
            if (existingFavorite.isPresent()) {
                // 取消收藏
                logger.info("用户{}取消收藏帖子{}", user.getUsername(), postId);
                favoriteRepository.delete(existingFavorite.get());
                
                // 确保收藏数不会小于0
                if (post.getFavoriteCount() > 0) {
                    postRepository.updateFavoriteCount(post.getId(), -1);
                }
                isFavorited = false;
            } else {
                // 收藏
                logger.info("用户{}收藏帖子{}", user.getUsername(), postId);
                Favorite favorite = new Favorite();
                favorite.setUser(user);
                favorite.setPost(post);
                favoriteRepository.save(favorite);
                postRepository.updateFavoriteCount(post.getId(), 1);
                isFavorited = true;
                
                // 发送收藏通知
                messageService.sendFavoriteNotification(user, postId);
            }
            
            // 查询最新的收藏数，确保数据准确
            post = postRepository.findById(postId).orElse(post);
            
            // 再次检查确保收藏数不为负数
            if (post.getFavoriteCount() < 0) {
                post.setFavoriteCount(0);
                postRepository.save(post);
                logger.info("修正帖子{}的收藏数为0", postId);
            }
            
            // 计算实际的收藏数，作为额外验证
            long actualFavoriteCount = favoriteRepository.countByPostId(postId);
            if (actualFavoriteCount != post.getFavoriteCount()) {
                logger.warn("帖子{}的收藏数不一致，数据库中显示{}，实际收藏数为{}", 
                            postId, post.getFavoriteCount(), actualFavoriteCount);
                post.setFavoriteCount((int)actualFavoriteCount);
                postRepository.save(post);
            }
            
            Map<String, Object> response = Map.of(
                "favoriteCount", post.getFavoriteCount(),
                "isFavorited", isFavorited
            );
            logger.info("返回结果: {}", response);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("处理收藏操作时发生错误: {}", e.getMessage(), e);
            return ResponseEntity.status(500).body(Map.of(
                "error", "处理收藏操作时发生错误",
                "message", e.getMessage()
            ));
        }
    }
    
    /**
     * 获取用户收藏的帖子列表
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getUserFavorites(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long userId,
            @RequestHeader(value = "Authorization", required = false) String token) {
        
        logger.info("获取收藏列表请求：page={}, size={}, userId={}, token={}", page, size, userId, token);
        
        // 尝试从请求参数中获取用户ID
        if (userId != null) {
            logger.info("使用请求参数中的userId: {}", userId);
            Optional<User> userOpt = userRepository.findById(userId);
            if (userOpt.isPresent()) {
                return getFavoritesByUserId(page, size, userId);
            } else {
                logger.warn("找不到指定ID的用户: {}", userId);
            }
        }
        
        // 尝试从请求头中获取token
        if (token == null || token.isEmpty()) {
            logger.warn("未提供Authorization头");
            return ResponseEntity.status(401).build();
        }
        
        // Bearer Token处理
        if (token.startsWith("Bearer ")) {
            logger.info("处理Bearer Token");
            token = token.substring(7);
        }
        
        Long userIdFromToken = null;
        try {
            // 尝试将token解析为用户ID
            userIdFromToken = Long.parseLong(token);
            logger.info("尝试将token作为用户ID解析: {}", userIdFromToken);
            if (!userRepository.findById(userIdFromToken).isPresent()) {
                logger.warn("找不到ID为{}的用户", userIdFromToken);
                return ResponseEntity.status(401).build();
            }
        } catch (NumberFormatException e) {
            // 如果token不是有效的用户ID，尝试按用户名查找
            logger.info("token不是数字，尝试作为用户名: {}", token);
            Optional<User> currentUser = userRepository.findByUsername(token);
            if (!currentUser.isPresent()) {
                logger.warn("找不到用户名为{}的用户", token);
                return ResponseEntity.status(401).build();
            }
            userIdFromToken = currentUser.get().getId();
            logger.info("通过用户名找到用户ID: {}", userIdFromToken);
        }
        
        return getFavoritesByUserId(page, size, userIdFromToken);
    }
    
    /**
     * 根据用户ID获取收藏列表
     */
    private ResponseEntity<Map<String, Object>> getFavoritesByUserId(int page, int size, Long userId) {
        logger.info("获取用户{}的收藏列表，页码={}, 每页={}", userId, page, size);
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Post> favoritePosts = favoriteRepository.findFavoritePostsByUserId(userId, pageable);
        
        // 转换为DTO并设置点赞和收藏状态
        final Long finalUserId = userId; // 创建一个final变量供lambda表达式使用
        List<PostDTO> postDTOs = favoritePosts.getContent().stream().map(post -> {
            PostDTO dto = convertToDTO(post);
            
            // 设置用户是否点赞和收藏
            Optional<Like> like = likeRepository.findByUserIdAndPostId(finalUserId, post.getId());
            dto.setIsLiked(like.isPresent());
            
            // 收藏列表中的帖子肯定是已收藏的
            dto.setIsFavorited(true);
            
            return dto;
        }).collect(Collectors.toList());
        
        Map<String, Object> response = new HashMap<>();
        response.put("posts", postDTOs);
        response.put("currentPage", favoritePosts.getNumber());
        response.put("totalItems", favoritePosts.getTotalElements());
        response.put("totalPages", favoritePosts.getTotalPages());
        
        logger.info("返回结果: {} 条收藏帖子", postDTOs.size());
        return ResponseEntity.ok(response);
    }
    
    /**
     * 将Post实体转换为PostDTO
     */
    private PostDTO convertToDTO(Post post) {
        PostDTO dto = new PostDTO();
        dto.setId(post.getId());
        dto.setTitle(post.getTitle());
        dto.setContent(post.getContent());
        
        dto.setViewCount(post.getViewCount());
        dto.setLikeCount(post.getLikeCount());
        dto.setFavoriteCount(post.getFavoriteCount());
        dto.setCommentCount(post.getCommentCount());
        dto.setStatus(post.getStatus());
        dto.setCreateTime(post.getCreateTime());
        dto.setUpdateTime(post.getUpdateTime());
        
        // 处理作者信息
        if (post.getUser() != null) {
            UserDTO authorDTO = new UserDTO();
            authorDTO.setId(post.getUser().getId());
            authorDTO.setUsername(post.getUser().getUsername());
            authorDTO.setNickname(post.getUser().getNickname());
            authorDTO.setAvatar(post.getUser().getAvatar());
            dto.setAuthor(authorDTO);
        }
        
        // 处理标签
        if (post.getTags() != null) {
            List<String> tagNames = post.getTags().stream()
                .map(tag -> tag.getName())
                .collect(Collectors.toList());
            dto.setTags(tagNames);
        } else {
            dto.setTags(new ArrayList<>());
        }
        
        return dto;
    }
} 